package com.yunquan.ohana.http.transformer

import com.yunquan.ohana.http.exception.ErrorType
import com.yunquan.ohana.http.exception.ExceptionEngine
import com.yunquan.ohana.http.exception.ServerException
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableSource
import io.reactivex.rxjava3.core.ObservableTransformer

/**
 * $
 * @author yjp
 * @date 2020/4/1 14:51
 */
class CallbackDataTransFormer<T : Any> private constructor() : ObservableTransformer<BaseResult<T>, T> {

    companion object {
        private var instance: CallbackDataTransFormer<*>? = null

        @Synchronized
        fun <T : Any> getInstance(): CallbackDataTransFormer<T> {
            if (instance == null) {
                synchronized(this) {
                    instance = CallbackDataTransFormer<T>()
                }
            }
            return instance as CallbackDataTransFormer<T>
        }
    }

    override fun apply(upstream: Observable<BaseResult<T>>): ObservableSource<T> {
        return upstream.map {
            if (it.code != ErrorType.SUCCESS || it.data == null) {
                throw ServerException(
                    it.code,
                    it.msg ?: "null"
                )
            }
            it.data!!
        }.onErrorResumeNext { throwable: Throwable ->
            // ExceptionEngine 为处理异常的驱动器 throwable
            val e = if (throwable.message?.contains("Unauthorized") == true) {
                ServerException(401, throwable.message!!)
            } else {
                throwable
            }
            Observable.error(ExceptionEngine.handleException(e))
        }
    }

}